const cloud = require('wx-server-sdk');

// const db = cloud.database({
// 	env:'roseannepark'
// })
const db = cloud.database()

const _ = db.command

exports.main = async (event, context) => {
	console.log(event);
	if (event.method === 'get') {
		let start = event.start;
		let datas = []
		let result = await db.collection('comment').where({
			mediaId: event.mediaId,
			user_id: _.exists(true)
		}).orderBy('created_at_utc', 'desc').limit(12).skip(start * 12).get();
		datas.push(...result.data)
		if(result.data.length < 6){
			let nresult = await db.collection('ins_comment').where({
				mediaId: event.mediaId,
				user_id: _.exists(true)
			}).orderBy('created_at_utc', 'desc').limit(12).skip(start * 12).get();
			datas.push(...nresult.data)
		}
		return {
			'msg': 'ok',
			'data': datas
		}
	} else {
		if(event.data.origin == 'mp-weixin'){
			const result = await cloud.openapi.security.msgSecCheck({
				"openid": event.data.user_id,
				"scene": 2,
				"version": 2,
				"content": event.data.text
			})
			if (result.result.label == 100) {
				await db.collection('comment').add({
					data: event.data
				});
				return {
					'msg': 'ok'
				}
			} else {
				return {
					'msg': 'fail'
				}
			}
		}else{
			await db.collection('comment').add({
				data: event.data
			});
			return {
				'msg': 'ok'
			}
		}
	}
}